<template>
  <div id="lottery-wrapper">
<!--    <a v-if="!openid" class="auth-modal" @click="getUserInfo"></a>-->
    <div class="flex align-center justify-center" style="height:100%">
      <div class="pd20">
        <div class="text-center mb20">
          <div class="pt10 pb10 pr20 pl20" style="border-radius:9999px;background: #fff;color:rgb(244,184,126);">
            剩<span class="mr5 ml5" style="color:#888;font-weight:bold">{{count}}</span>次抽奖机会
          </div>
        </div>
        <!-- 大转盘抽奖 -->
        <LuckyWheel
          style="margin: 0 auto;"
          ref="LuckyWheel"
          :width="width"
          :height="height"
          :prizes="prizes"
          :default-style="defaultStyle"
          :blocks="blocks"
          :buttons="buttons"
          @start="startCallBack"
          @end="endCallBack"
        />
        <van-row class="text-center mt20" gutter="20">
          <van-col span="12">
            <div class="pt10 pb10 pr20 pl20"
                  style="border-radius:9999px;background: #fff;color:rgb(244,184,126);"
                  @click="showDescription = true">
              活动规则
            </div>
          </van-col>
          <van-col span="12">
            <div class="pt10 pb10 pr20 pl20"
                  style="border-radius:9999px;background: #fff;color:rgb(244,184,126);"
                  @click="jumpToMyPrize">
              我的奖品
            </div>
          </van-col>
        </van-row>
      </div>
    </div>
    <!-- 再接再厉 -->
    <van-overlay :show="showWish">
      <div class="flex align-center justify-center" style="height: 100%">
        <div class="close-wrapper position-relative" style="height:40%">
          <van-icon name="close" @click="showWish = false" />
          <img style="height: 100%" src="../../../assets/image/christmas2.jpg">
        </div>
      </div>
    </van-overlay>
    <van-popup v-model="showDescription" position="bottom" :style="{ height: '50%' }">
      <p class="description">
        活动规则：<br/>
        1.活动期间每个用户最多可参与抽奖1次<br/>
        2.奖品设置：10元优惠券，95折优惠券，精美小礼品<br/>
        3.精美小礼品请在门店现场领取，详情请咨询店员<br/>
        4.广州车陂店不参与活动，领取奖品仅限海口市、大连市万国小厨门店<br/>
      </p>
    </van-popup>
  </div>
</template>

<script>
  import Vue from 'vue'
  import { getJsSignature } from '@/api/wxmp/jssdk'
  import h5 from '@/api/h5'
  import { Dialog, Toast, Icon, Button, Overlay, Popup, Col, Row, Cell, RadioGroup, Radio } from 'vant'
  import 'vant/lib/dialog/style'
  import 'vant/lib/toast/style'
  import 'vant/lib/button/style'
  import 'vant/lib/icon/style'
  import 'vant/lib/overlay/style'
  import 'vant/lib/popup/style'
  import 'vant/lib/col/style'
  import 'vant/lib/row/style'

  export default {
    name: 'Lottery',
    components: {
      "van-icon": Icon,
      'van-button': Button,
      "van-overlay": Overlay,
      "van-popup": Popup,
      "van-row": Row,
      "van-col": Col,
      "van-cell": Cell
    },
    data() {
      return {
        showDescription: false,
        showWish: false,
        loaded: false,
        width: '',
        height: '',
        count: 1,
        pageInfo: {},
        openid: '',
        prizes: [],
        defaultStyle: {
          fontColor: '#d64737',
          fontSize: '14px'
        },
        blocks: [
          { padding: '13px', background: '#d64737' }
        ],
        // 抽奖按钮
        buttons: [
          { radius: '50px', background: '#d64737' },
          { radius: '45px', background: '#fff' },
          { radius: '41px', background: '#f6c66f', pointer: true },
          {
            radius: '35px', background: '#ffdea0',
            fonts: [{text: '点击\n抽奖', top: '-60%', fontWeight: 700, lineHeight: '18px'}]
          }
        ],
        lock: false,
        pageId: '',
        appId: '',
        comAppid: 'wxbb4d1b1668fa25f3',
        redirect: 'http://wechat.corner-s.com/ssm-api/mp/js/authorize'
      }
    },
    computed: {
      authUrl() {
        let url = encodeURIComponent(this.redirect)
        let appId = this.appId
        let comAppid = this.comAppid
        return `https://open.weixin.qq.com/connect/oauth2/authorize?component_appid=${comAppid}&appid=${appId}&redirect_uri=${url}&response_type=code&scope=snsapi_userinfo&state=snsapi_userinfo#wechat_redirect`
      }
    },
    beforeMount() {
      this.width = (document.body.clientWidth)/4*3 + 'px'
      this.height = (document.body.clientHeight/2) + 'px'
    },
    created() {
      console.log('created')
      Dialog.alert({
        message: '活动已结束'
      })
      // this.load()
    },
    activated() {
      console.log('activated')
      //this.load()
    },
    methods: {
      getUserInfo() {
        Toast.loading({
          message: '登录中',
          duration: 0,
          loadingType: 'spinner',
          onOpened: () => {
            location.href = this.authUrl
          }
        })
      },
      load() {
        this.appId = this.$route.query.appId
        this.pageId = this.$route.query.pageId
        this.openid = localStorage.getItem('openid')
        if (!this.openid || this.openid === "undefined") {
          this.openid = this.$route.query.openid
          localStorage.setItem('openid', this.openid)
        }
        // 获取页面信息，判断活动是否进行
        Toast.loading({
          message: '加载中',
          duration: 0,
          forbidClick: true,
          loadingType: 'spinner',
          onOpened: () => {
            h5.getPageInfo(this.pageId, this.openid).then(res => {
              if (res.data.play) {
                this.count = 0
              }
              Toast.clear();
              let now = this.$moment().format("YYYY-MM-DD")
              this.loaded = now >= res.data.page.beginTime && now <= res.data.page.endTime
              this.loaded = true
              res.data.coupon.forEach((item, index) => {
                this.prizes.push({
                  id: item.id,
                  title: item.name,
                  type: item.couponType,
                  background: index % 2 ? '#f9e3bb' : '#f8d384',
                  fonts: [{ text: item.name, top: '30%' }],
                })
              })
            })
          }
        })
      },
      jumpToMyPrize () {
        this.$router.push({ path: "/h5/coupon/list", query: { pageId: this.pageId, openid: this.openid }})
      },
      startCallBack () {
        return Dialog.alert({
          message: '活动已结束'
        })
        if (this.count == 0) {
          return Toast.fail("已经没有抽奖机会啦")
        }
        if (!this.lock) {
          this.lock = true
          h5.getStock(this.pageId).then(res => {
            console.log(res)
            this.prizes.forEach((item, index) => {
              item.stock = res.data[item.id]
            })
            console.log(this.prizes)
            this.$refs.LuckyWheel.play()
            setTimeout(() => {
              let prizes = this.prizes.filter(item => item.stock > 0 || item.stock === "")
              console.log(prizes)
              this.$refs.LuckyWheel.stop(Math.random() * prizes.length-1 >> 0)
              this.lock = false
            }, 3000)
          }).catch(_ => {
            this.lock = false
          })
        }
      },
      endCallBack (prize) {
        Toast.loading({
          message: '加载中',
          forbidClick: true,
          loadingType: 'spinner',
          onOpened: () => {
            h5.play(this.pageId, this.openid).then(res => {
              this.count--
              if (prize.type == 'cash' || prize.type == 'gift') {
                h5.lockCouponCode({
                  pageId: Number(this.pageId),
                  couponId: prize.id,
                  openid: this.openid
                }).then(res => {
                  Dialog.confirm({
                    message: `恭喜您获得${prize.title}`,
                    confirmButtonText: '领取',
                    cancelButtonText: '放弃'
                  }).then(() => {
                    h5.receiveCouponCode({
                      couponId: res.data.couponId,
                      code: res.data.couponCode,
                      pageId: this.pageId
                    }).then(res => {
                      Toast.success({
                        message: '领取成功',
                        duration: 1000
                      })
                    })
                  }).catch(() => {
                    h5.unlockCouponCode({
                      couponId: res.data.couponId,
                      code: res.data.couponCode,
                      pageId: this.pageId
                    })
                  })
                }).catch(res => {
                  console.log(res)
                  Dialog.alert({
                    message: res.data.msg
                  }).then(() => {
                    this.count++
                  })
                })
              } else if (prize.type === 'wish') {
                Toast.clear()
                this.showWish = true
              }
            })
            // if (prize.couponType == 'cash') {
            //   // 获取可用的code
            //   getCardCode({
            //     cardId: prize.cardId,
            //     openid: this.openid
            //   }).then(res => {
            //     // 签名
            //     getCardApiSignature({
            //       code: res.data.code,
            //       cardId: prize.cardId,
            //       appId: this.appId
            //     }).then(res => {
            //       Dialog.alert({
            //         message: `恭喜您获得${prize.name}`,
            //         confirmButtonText: '去领取'
            //       }).then(() => {
            //         this.$wechat.addCard({
            //           cardList: [{
            //             cardId: prize.cardId,
            //             cardExt: JSON.stringify({
            //               code: res.data.code,
            //               nonce_str: res.data.nonceStr,
            //               timestamp: res.data.timestamp,
            //               signature: res.data.signature
            //             })
            //           }],
            //           success: function (res) {
            //             console.log('领取成功', res)
            //           }
            //         })
            //       })
            //     })
            //   })
            // } else if (prize.couponType == 'gift') {
            //   getCardApiSignature({
            //     cardId: prize.cardId,
            //     appId: this.appId
            //   }).then(res => {
            //     Dialog.alert({
            //       message: `恭喜您获得${prize.name}`,
            //       confirmButtonText: '去领取'
            //     }).then(() => {
            //       this.$wechat.addCard({
            //         cardList: [{
            //           cardId: prize.cardId,
            //           cardExt: JSON.stringify({
            //             nonce_str: res.data.nonceStr,
            //             timestamp: res.data.timestamp,
            //             signature: res.data.signature
            //           })
            //         }],
            //         success: function (res) {
            //           console.log('领取成功', res)
            //         }
            //       })
            //     })
            //   })
            // } else if (prize.couponType == 'wish') {
            //   Dialog.alert({
            //     message: `祝您${prize.name}`
            //   })
            // }
          }
        })
      },
      setConfig() {
        const url = location.href.split('#')[0]
        getJsSignature(this.appId, url).then(res => {
          let config = {
            appId: res.data.appId,
            timestamp: res.data.timestamp,
            nonceStr: res.data.nonceStr,
            signature: res.data.signature,
            jsApiList: [
              'checkJsApi',
              'onMenuShareTimeline',
              'onMenuShareAppMessage',
              'onMenuShareQQ',
              'onMenuShareWeibo',
              'onMenuShareQZone',
              'hideMenuItems',
              'showMenuItems',
              'hideAllNonBaseMenuItem',
              'showAllNonBaseMenuItem',
              'translateVoice',
              'startRecord',
              'stopRecord',
              'onVoiceRecordEnd',
              'playVoice',
              'onVoicePlayEnd',
              'pauseVoice',
              'stopVoice',
              'uploadVoice',
              'downloadVoice',
              'chooseImage',
              'previewImage',
              'uploadImage',
              'downloadImage',
              'getNetworkType',
              'openLocation',
              'getLocation',
              'hideOptionMenu',
              'showOptionMenu',
              'closeWindow',
              'scanQRCode',
              'chooseWXPay',
              'openProductSpecificView',
              'addCard',
              'chooseCard',
              'openCard'
            ]
          }
          this.$wechat.ready(() => {
            console.log('签名验证成功')
          })
          this.$wechat.config(config)
        })
      }
    }
  }
</script>

<style scoped>
  #lottery-wrapper {
    color: #f5f5f5;
    background-image: url("../../../assets/image/christmas.jpg")!important;
    background-repeat:  repeat-x;
    background-size: contain;
    background-position: center;
    height: 100%;
    width: 100%;
    overflow: hidden;
  }
  .description {
    background-image: url("../../../assets/image/christmas.jpg")!important;
    background-repeat:  repeat-x;
    background-size: contain;
    background-position: center;
    height: 100%;
    color: #eee;
    line-height: 2;
    padding: 10px;
  }
  .close-wrapper {
    position: relative;
  }
  .close-wrapper .van-icon-close {
    position: absolute;
    display: inline-block;
    width: 32px;
    height: 32px;
    font-size: 32px;
    z-index: 9999;
    bottom: -16px;
    left: 50%;
    transform: translate(-50%, 100%);
  }
</style>
